import React, { useState, useEffect } from "react";
import { connect } from "react-redux";
import { Toast } from "antd-mobile";
import MainLayout from "@/component/mainLayout/mainLayout";
import Banner from "./components/banner";
import Form from "./components/form";
import yhTools from "@/tools/yh";
import creditStore from "../creditStore";
import { InterfaceG } from "@/config/Config";
import "./index.scss";

const TwoElement = props => {
	const [formValues, setFormValues] = useState({});
	const [disabled, setDisabled] = useState(false);
	const [imgUrlData, setImgUrlData] = useState({});
	const { productNum, isHiddenBotton } = props;
	const submitHandle = async values => {
		props.trim(values);
		let objs = {
			url: InterfaceG.xhdSaveTwoElement,
			params: {
				productNum,
				...values
			}
		};
		if (disabled) {
			props.goNext();
		} else {
			try {
				Toast.loading("加载中...");
				const { code, message } = await yhTools.request(objs);
				Toast.hide();
				if (code === "0") {
					props.goNext();
				} else {
					Toast.info(message, 2);
				}
			} catch (error) {
				Toast.fail(error ? error.message : "");
			}
		}
	};

	//查询身份证信息
	const xhdQueryTwoElement = async () => {
		let objs = {
			url: InterfaceG.xhdQueryTwoElement,
			params: {
				productNum
			}
		};
		try {
			Toast.loading("加载中...");
			const { data, code } = await yhTools.request(objs);
			if (code === "0" && data && data.userName && data.idNo) {
				setFormValues(data);
				setDisabled(true);
			}
		} catch (error) {
			Toast.fail(error ? error.message : "");
		} finally {
			Toast.hide();
		}
	};
	//查询banner
	const getChannelBannerList = async () => {
		let objs = {
			url: InterfaceG.getBannerListByPageType,
			params: {
				pageType: "xhdTelementPage"
			}
		};
		try {
			const { data, code } = await yhTools.request(objs);
			if (code === "0") {
				if (data && data.length > 0) {
					data.forEach(item => {
						if (item.bannerType == "topBanner") {
							setImgUrlData(item.indexServerDtos[0] || {});
						}
					});
				}
			}
		} catch (error) {
			Toast.fail(error ? error.message : "");
		}
	};
	useEffect(() => {
		xhdQueryTwoElement();
		getChannelBannerList();
	}, []);

	const headerParams = {
		header: {
			title: "实名认证"
		},
		isModal: true,
		history: props.history,
		cacheLifecycles: props.cacheLifecycles
	};

	return (
		<MainLayout pageParams={headerParams} handleBack={props.handleBack}>
			<div className="two-element-wrapper">
				<Banner imgUrlData={imgUrlData} />
				<Form
					{...props}
					disabled={disabled}
					values={formValues}
					submit={submitHandle}
					isHiddenBotton={isHiddenBotton}
					currentCode={props.currentCode}
				/>
			</div>
		</MainLayout>
	);
};
const mapStateToProps = state => state;

export default connect(mapStateToProps)(creditStore(TwoElement));
